import React, {Component} from "react";
import router from "umi/router";
import {Row, Steps, Menu, Dropdown, Popconfirm} from "antd";
// import cn from "classnames";
import {isPhone, openNotificationWithIcon} from 'utils/comm';
import ReissueConfigComponent from "components/flowdataDetail/ReissueConfigComponent";
import RecordDetail from "./RecordDetail";
import SecondProcessRecord from "./SecondProcessRecord";
import styles from "./ProcessRecord.less";


const {Step} = Steps;

/* const mockStep = 2;
const mockData = [
  {
    taskNodeTime: "2019-06-09 12:30",
    operator: "张三",
    tasName: "发起流程",
    approval: "通过",
    status: "正常",
    taskNodeType: "start",
    taskStatus: "已处理",
    activityId: "t_b_1596770",
  },
  {
    taskNodeTime: "2019-06-09 12:30",
    operator: "李四",
    tasName: "分局审批",
    approval: "通过",
    status: "正常",
    taskNodeType: "node",
    taskStatus: "已处理",
    activityId: "t_b_1596771",
  },
  {
    taskNodeTime: "2019-06-09 12:30",
    operator: "张三",
    tasName: "分局审批",
    approval: "通过",
    status: "正常",
    taskNodeType: "node",
    taskStatus: "待处理",
    activityId: "t_b_1596772",
  },
  {
    taskNodeTime: "2019-06-09 12:30",
    operator: ["张三", "李四", "王二", "吴一"],
    tasName: "i派出所审批",
    status: "预警",
    taskNodeType: "end",
    taskStatus: "待处理",
    activityId: "t_b_1596773",
    processInstanceId: "bd27177ddaa711e9b3be005056a0b338",
  },
]; */
// const Status = {
//   NORMAL: "正常",
//   WARNING: "预警",
//   TIMEOUT: "超时",
//   END: "终止",
//   PAUSE: "暂停",
//   RECALL: "撤销",
//   ERROR: "错误",
// };

class ProcessRecord extends Component {
  state = {
    visible: false,
    activityId: "",
    taskId: null,
    secondVisible: null,
    showReissueConfig: false,
    reissueTaskId: '',
  };

  takeBackTaskIDs = [];

  reissueTaskIDs = [];

  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
    this.renderItem = this.renderItemWithCurrentId.bind(
      this,
      this.onDetail,
      this.toggleSecond,
    );

  }

  // renderHandle = (onDetail, item, operator) => {
  renderHandle = (onDetail, item) => {
    const {handleTaskVisible, customFormVisible, actype} = this.props;

    const {nodeAuth} = item;
    let showMore = false;

    if (nodeAuth) {
      showMore =
        nodeAuth.addSignature ||
        nodeAuth.delay ||
        nodeAuth.signIn ||
        nodeAuth.reject ||
        nodeAuth.transfer;
    }

    const Detail = (
      <span className={styles.detail} onClick={() => onDetail(item)}>
        详情
      </span>
    );

    const SIGNIN = (
      <>
        <span className={styles.detail} onClick={() => onDetail(item)}>
          详情
        </span>
        <span
          className={styles.detail}
          onClick={() => {
            handleTaskVisible("signVisible", true, item.taskId);
          }}
        >
          签收
        </span>
      </>
    );

    const menu = showMore ? (
      <Menu>
        {nodeAuth.addSignature && (
          <Menu.Item>
            <span
              onClick={() => {
                handleTaskVisible("addSignVisible", true, item.taskId);
              }}
            >
              加签
            </span>
          </Menu.Item>
        )}
        {nodeAuth.transfer && (
          <Menu.Item>
            <span
              onClick={() => {
                handleTaskVisible("transferVisible", true, item.taskId);
              }}
            >
              转办
            </span>
          </Menu.Item>
        )}
        {nodeAuth.delay && (
          <Menu.Item>
            <span
              onClick={() => {
                handleTaskVisible("delayVisible", true, item.taskId);
              }}
            >
              延期
            </span>
          </Menu.Item>
        )}
        {nodeAuth.reject && (
          <Menu.Item>
            <span
              onClick={() => {
                handleTaskVisible("rejectVisible", true, item.taskId);
              }}
            >
              驳回
            </span>
          </Menu.Item>
        )}
      </Menu>
    ) : null;

    const HandleAndMORE = (
      <>
        <span
          className={styles.detail}
          onClick={() => {
            if (isPhone()) {
              router.push(`/embedded/phone/todo-detail/form?taskId=${item.taskId}&editable=1`);
            } else {
              customFormVisible(true, item);
            }
          }}
        >
          处理
        </span>
        {showMore && (
          <Dropdown overlay={menu} placement="bottomRight">
            <span className={styles.detail}>更多</span>
          </Dropdown>
        )}
      </>
    );

    if (actype === "todo") {
      // if (item.taskStatus === "TODO" && !operator) {
      if (item.taskStatus === "TODO" && nodeAuth.signIn) {
        return SIGNIN;
      } else if (
        item.nodeAuthShow &&
        item.taskStatus === "TODO" &&
        !item.multiInstance
      ) {
        return HandleAndMORE;
      } else if (item.taskId && !item.multiInstance) {
        return Detail;
      }
    } else if (actype !== "todo") {
      if (item.taskId && !item.multiInstance) {
        return Detail;
      }
    }
  };

  handleTakeBack = (taskId) => {

    if (!taskId || taskId === '') {
      return;
    }

    const {dispatch, getFlowRecords} = this.props;
    const userCode = sessionStorage.getItem("USER_CODE") ?? '';


    dispatch({
      type: "FlowHandle/takeBack",
      payload: {
        taskId,
        userCode,
        comment: '',
      },
    }).then(({errCode, errMsg}) => {
      if (errCode === 0) {
        this.openNotificationWithIcon("success", "", "拿回成功");
        // this.getDetailData();

        if (getFlowRecords && (getFlowRecords instanceof Function)) {
          getFlowRecords()
        }

      } else {
        this.openNotificationWithIcon("error", "", errMsg || "拿回失败");
      }
    })
  }

  handleReissue = () => {
    this.setState({showReissueConfig: false});
  }

  renderItemWithCurrentId = (onDetail, toggleSecond, item, index) => {
    // const statusClassName = item.status === "NORMAL" ? "" : styles.error;
    // const resultClassName = styles[item.approval === "通过" ? "ok" : "error"];
    const {secondVisible} = this.state;
    const {handleTaskVisible, actype, customFormVisible} = this.props;

    const isDealFinish =
      Number(item.numOfHandler) - Number(item.numOfCompleted);
    const operator =
      Array.isArray(item.operators) && item.operators.length > 0
        ? item.operators.length > 3
          ? `${item.operators.slice(0, 3).join("、")}...`
          : item.operators.join("、")
        : item.operator;

    return (
      <Step
        title={
          <div>
            <div className={styles.desc}>
              <span style={{width: "170px"}}>
                {item.taskNodeTime || "--"}
              </span>
              <span style={{width: "220px"}}>
                节点名称：
                <span>{item.taskName}</span>
                {item.multiInstance && <span>(会签)</span>}
              </span>

              {item.taskNodeType === "node" ? (
                <>
                  <span style={{width: "200px"}}>
                    <span className={styles.mr16}>
                      处理状态：
                      {item.taskStatus === "DONE" ? "已处理" : "待处理"}
                    </span>
                    {/* <span className={statusClassName}>
                      {Status[item.status]}
                    </span> */}
                  </span>
                  {/* {item.taskName === "审批节点" ||
                  (item.multiInstance && item.approval) ? (
                    <span>
                      <span className={styles.mr16}>审批结果：</span>
                      <span className={resultClassName}>{item.approval}</span>
                    </span>
                  ) : null} */}
                </>
              ) : null}

              <span style={{width: "200px"}}>
                {operator ? `操作人：${operator}` : ``}
              </span>


              {this.takeBackTaskIDs && Array.isArray(this.takeBackTaskIDs) && this.takeBackTaskIDs.indexOf(item.taskId) !== -1 && !item.multiInstance ? (

                <Popconfirm
                  title="确定拿回吗？"
                  okText="确定"
                  cancelText="取消"
                  onConfirm={() => this.handleTakeBack(item.taskId)}
                >
                  <span className={styles.detail}>拿回</span>
                </Popconfirm>

              ) : (
                <span
                  className={styles.detail}
                />
              )}

              { this.reissueTaskIDs && Array.isArray(this.reissueTaskIDs) && this.reissueTaskIDs.indexOf(item.taskId) !== -1 && !item.multiInstance  ? (

                <span
                  className={styles.detail}
                  onClick={() => {
                    this.setState({reissueTaskId: item.taskId}, () => {
                      this.setState({showReissueConfig: true});
                    })
                  }}
                >
                  补发
                </span>

              ) : (
                <span
                  className={styles.detail}
                />
              )}

              {this.renderHandle(onDetail, item, operator)}

              {item.multiInstance && (
                <span
                  className={styles.detail}
                  onClick={() => toggleSecond(item.taskId)}
                >
                  {item.taskId === secondVisible ? "收起" : "展开"}
                </span>
              )}
            </div>
            {item.multiInstance && (
              <div
                className={styles.processRecord}
                style={{
                  display: item.taskId === secondVisible ? "block" : "none",
                }}
              >
                <div className={styles.processRecordTitle}>
                  <span style={{width: "190px"}}>
                    <span>任务派发：</span>
                    <span>{`${item.numOfInstances}人`}</span>
                  </span>
                  <span style={{width: "240px"}}>
                    <span>需处理：</span>
                    <span>{`${item.numOfHandler}人`}</span>
                  </span>
                  <span style={{width: "200px"}}>
                    <span>已处理：</span>
                    <span>{`${item.numOfCompleted}人`}</span>
                  </span>
                </div>
                <div style={{padding: "0 8px"}}>
                  <SecondProcessRecord
                    data={item.children}
                    isDealFinish={isDealFinish}
                    handleTaskVisible={handleTaskVisible}
                    customFormVisible={customFormVisible}
                    actype={actype}
                    nodeAuth={item.nodeAuth}
                    // renderHandle={this.renderHandle}
                    takeBackTaskIDs={this.takeBackTaskIDs}
                    reissueTaskIDs={this.reissueTaskIDs}
                    handleTakeBack={(taskId => this.handleTakeBack(taskId))}
                    handleReissue={reissueTaskId => this.setState({reissueTaskId}, () => {
                      this.setState({showReissueConfig: true});
                    })}
                  />
                </div>
              </div>
            )}
          </div>
        }
        // title={item.taskNodeTime}
        key={index}
      />
    );
  };

  onDetail = ({activityId, taskId}) => {

    if (isPhone()) {
      router.push(`/embedded/phone/todo-detail/form?taskId=${taskId}`);
    } else {
      this.setState({
        activityId,
        visible: true,
        taskId,
      });
    }
  }

  toggleSecond = (taskId) => {
    const {secondVisible} = this.state;
    this.setState({
      secondVisible: secondVisible === taskId ? null : taskId,
    });
  };

  render() {
    const {visible, activityId, taskId, showReissueConfig, reissueTaskId} = this.state;
    const {flowRecords = [], data = {}, dispatch, appId, location = {}, getFlowRecords} = this.props;
    // console.log("flowRecords------------", flowRecords, data);

    const {pathname = ''} = location;
    if (pathname === '/taskcenter/detail') {
      this.takeBackTaskIDs = [];
      this.reissueTaskIDs = [];

        flowRecords.map((item, index) => {

          const {taskStatus = '', nodeAuth, children = []} = item || {};

          if (children.length > 0) {
            children.map((subItem, subItemIndex) => {

                if (!(subItemIndex === children.length - 1 && index === flowRecords.length - 1)) {
                  if (subItem.taskStatus === 'DONE' && subItem.nodeAuth) {
                    const {takeBack = false, reissue = false} = subItem.nodeAuth;
                    if (takeBack) {
                      this.takeBackTaskIDs = [...this.takeBackTaskIDs, subItem.taskId];
                    }
                    if (reissue) {
                      this.reissueTaskIDs = [...this.reissueTaskIDs, subItem.taskId];
                    }
                  }
                  // // 会签节点的最后一个也是该任务的最后一个节点时, 不展示拿回和补发
                  // if (subItemIndex === children.length - 1 && index === maxLength) {
                  //   this.takeBackTaskIDs = [];
                  //   this.reissueTaskIDs = [];
                  // }
                }
                return subItem;
              }
            )
          } else if (taskStatus === 'DONE' && nodeAuth && index !== flowRecords.length - 1) {
            const {takeBack = false, reissue = false} = nodeAuth;
            if (takeBack) {
              this.takeBackTaskIDs = [...this.takeBackTaskIDs, item.taskId];
            }
            if (reissue) {
              this.reissueTaskIDs = [...this.reissueTaskIDs, item.taskId];
            }

            // 避免最后一个节点展示拿回和补发
            // if (index === maxLength) {
            //   this.takeBackTaskIDs = [];
            //   this.reissueTaskIDs = [];
            // }
          }

          return item;
        }
      )
    }



    const {processInstanceId}= data;
    let currentStep = 0;
    let type;
// let typeNodeIndex = 0;
    if (flowRecords.length) {
      for (const [i, record] of flowRecords.entries()) {
        type = record.taskNodeType;
        if (type === "start" || type === "end") {
          currentStep += 1;
          /* } else if (type === "end") {
            currentStep += 2;
            break; */
        } else if (record.taskStatus === "DONE") {
          // typeNodeIndex += 1;
          currentStep += 1;
        } else if (record.taskStatus === "TODO") {
          /*
          typeNodeIndex += 1;
          // 第1和2个非开始及结束类型， 状态为TODO,通知业务系统填充数据
          if (typeNodeIndex === 1) {
            record.noticeBusinessSystem = true;
            const next = flowRecords[i+1];
            if (next) {
              next.noticeBusinessSystem = true;
            }
          }
          */
          currentStep = i;
          break;
        }
      }
    }
    return (
      <>
        <Row className={styles.root}>
          <Steps direction="vertical" current={currentStep}>
            {/* mockData.map(this.renderItem) */}
            {flowRecords.length && flowRecords.map(this.renderItem)}
          </Steps>
          <RecordDetail
            activityId={activityId}
            taskId={taskId}
            onCancel={() => this.setState({visible: false})}
            processInstanceId={processInstanceId}
            visible={visible}
          />
        </Row>

        <ReissueConfigComponent
          appId={appId}
          dispatch={dispatch}
          getFlowRecords={getFlowRecords}
          processInstanceId={processInstanceId}
          taskId={reissueTaskId}
          visible={showReissueConfig}
          handleClose={() => this.setState({showReissueConfig: false})}
        />

      </>
    );
  }
}

export default ProcessRecord;
